import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param grid int整型ArrayList<ArrayList<>>
     * @return int整型
     */
    private boolean flg = true ;
    public int rotApple (ArrayList<ArrayList<Integer>> grid) {
        // write code here
        // write code here
        int[][] array = new int[grid.size()][grid.get(0).size()] ;
        for (int i = 0 ; i < array.length ; i++) {
            for (int j = 0 ;  j < grid.get(i).size() ; j ++) {
                array[i] [j] = grid.get(i).get(j);
            }
        }
        int secend = 0 ;
        while(flg) {
            flg = false ;
            for (int i = 0 ; i < array.length ; i++) {
                for (int j = 0 ; j < array[0].length ; j++) {
                    isHave(array , i , j) ;
                }
            }
            for (int i = 0 ; i < array.length ; i++) {
                for (int j = 0 ; j < array[0].length ; j++) {
                    if (array[i][j] == 3) {
                       array[i][j] = 2 ;
                    }
                }
            }
            if(flg == false){
                break ;
            }
            secend ++ ;
        }
        for (int i = 0 ; i < array.length ; i++) {
            for (int j = 0 ; j < array[0].length ; j++) {
                if (array[i][j] == 1) {
                   return -1 ;
                }
            }
        }




        return secend ;


    }
    private void isHave(int[][] array, int x, int y) {

        if (array[x][y] == 2 || array[x][y] == 0) {
            return  ;
        }
        if (x - 1 >= 0 && array[x - 1][y] == 2) {
            flg = true ;
            array[x][y] = 3 ;
            return  ;
        }
        if (y - 1 >= 0 && array[x][y - 1] == 2) {
            array[x][y] = 3 ;
            flg = true ;
            return  ;
        }
        if (x + 1 < array.length && array[x + 1][y] == 2) {
            flg = true ;
            array[x][y] = 3 ;
            return  ;
        }
        if (y + 1 < array[0].length && array[x][y] == 2) {
            flg = true ;
            array[x][y] = 3 ;
            return  ;
        }
    }

}